<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>人员管理</title>
    <link rel="stylesheet" th:href="@{/css/admin/base.css}">
    <link rel="stylesheet" th:href="@{/lib/flatpickr/flatpickr.min.css}">
    <link rel="stylesheet" th:href="@{/css/admin/app.css}">

</head>

<body class="page-device">
<div class="app-page">
    <div class="app-page-header">
        <div class="page-title">
            <div class="title">人员</div>
        </div>
    </div>

    <div class="app-page-content">

        <div class="app-card">
            <div class="app-card-body">
                <!-- 过滤器 -->
                <div class="filter" style="display: none;" data-checkUser>
                    <!-- 选项切换 -->
                    <div class="form-item">
                        <div class="form-group">
                            <label for="">部门：</label>
                            <div class="input-icon">
                                <input type="text" value="" disabled="disabled" class="departmentId z-hide" name='departmentId'>
                                <input type="text" placeholder="请选择部门" value="" disabled="disabled" class="departmentName" name='departmentName'>
                                <i class="fa fa-align-center select-dept"></i>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="">用户信息：</label>
                            <input type="text" placeholder="请输入用户姓名/手机/邮箱" name="search" class="search">
                        </div>
                    </div>

                    <button class="z-btn z-primary" id="doFilter">查询</button>
                </div>

                <div class="z-btn-group">
                    <button data-state="2" class="j-btn-control z-btn z-default add-account z-hide" data-addUser>添加用户</button>
                    <button data-state="2" class="j-btn-control z-btn z-default del-account " data-delUser>批量删除</button>
                    <button data-state="2" class="j-btn-control z-btn z-default enable-account " data-enableUser>批量启用</button>
                    <button data-state="2" class="j-btn-control z-btn z-default disable-account " data-enableUser>批量停用</button>
                    <button data-state="1" class="j-btn-control z-btn z-default import z-hide" data-batchImport>批量导入</button>
                    <button data-state="1" class="j-btn-control z-btn z-default downloadTemp z-hide" data-batchImport>下载批量导入模板</button>

                    <input type="file" multiple name="file" class="z-hide">
                </div>
            </div>
        </div>


        <div class="app-card ">
            <div class="app-card-body">

                <!-- 列表数据 -->
                <div class="z-table-con">
                    <table class="z-table">
                        <thead>
                        <th>
                            <input type="checkbox" class="j-checkbox-all">
                        </th>
                        <th>账号</th>
                        <th>性别</th>
                        <th>部门</th>
                        <th>角色</th>
                        <th>姓名</th>
                        <th>邮箱</th>
                        <th>手机号</th>
                        <th>状态</th>
                        <th>操作</th>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                    <div class="z-page z-pat">

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 添加部门 -->
<div class="popup-default z-popup z-fixed z-df z-flex-cc z-hide">
    <div class="bg" data-popup-close></div>
    <!--添加用户 -->
    <div class="popup-add-acount section z-hide">
        <div class="title">添加用户</div>
        <div class="content" id="userForm">
            <form>
                <div class="form-item z-hide">
                    <div class="label">
                        <label>ID</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" placeholder="" class="userId" name='userId'>
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>账号</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" placeholder="请输入账号，如abcD123" class="userName" name="userName" data-name="用户名" data-rule="required,length" minlength="5" maxlength="32">

                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>真实姓名</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" placeholder="请输入姓名" class="realName" name="realName" data-name="真实姓名" data-rule="length" maxlength="32">

                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>性别</label>
                    </div>
                    <div class="body" data-limit="0" data-input-name="" data-data-key="resize">
                        <select name="sex" id="" class="sex">
                            <option value="0">女</option>
                            <option value="1">男</option>
                        </select>
                    </div>
                </div>

                <div class="form-item row">
                    <div class="label">
                        <label>登录密码</label>
                    </div>
                    <div class="body" data-limit="0" data-input-name="" data-data-key="resize">
                        <input type="text" value="" placeholder="请输入登陆密码" class="password" name="password" data-name="登录密码" data-rule="required,length" minlength="6" maxlength="32">
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>民族</label>
                    </div>
                    <div class="body" data-limit="0" data-input-name="" data-data-key="resize">
                        <select value="" class="nation" name="nation">
                            <option value="0">--请选择--</option>
                        </select>
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>身份证</label>
                    </div>
                    <div class="body" data-limit="0" data-input-name="" data-data-key="resize">
                        <input type="text" value="" placeholder="请输入身份证" class="idCard" name="idCard">
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>所属部门</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" disabled="disabled" class="departmentId z-hide" name='departmentId'>
                        <input type="text" value="" disabled="disabled" class="departmentName" name='departmentName'>
                        <button class="z-btn z-default select-btn select-dept">选择</button>
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>岗位</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" class="post" name='post'>
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>角色</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" disabled="disabled" class="roleIds z-hide" name='roleIds'>
                        <input type="text" value="" disabled="disabled" class="roleNames" name='roleNames'>
                        <button class="z-btn z-default select-btn select-role">选择</button>
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>邮箱</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" placeholder="请输入邮箱" class="email" name="email"></div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>手机号</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" placeholder="请输入手机号" class="telephone" name="telephone"></div>
                </div>
            </form>
            <div class="z-btn-group">
                <a class="btn-sub z-btn z-primary user-comfirm">确定</a>
                <a class="z-btn z-default" data-popup-close>取消</a>
            </div>
        </div>
    </div>
</div>

<script th:src="@{/lib/jquery.min.js}"></script>
<script th:src="@{/lib/layer-v3.1.1/layer/layer.js}"></script>
<script th:src="@{/js/upload.js}"></script>
<script th:src="@{/js/popup.js}"></script>
<script th:src="@{/js/form.js}"></script>
<script th:src="@{/js/admin/app.js}"></script>
<script th:src="@{/js/pagination.js}"></script>
<script th:src="@{/lib/CryptoJS3/rollups/md5.js}"></script>

<script>

    var zTable = null,
        pageParams = {
            departmentId: '',
            roleId: '',
            search: ''
        },
        userOptType = 1,    // 1，添加  2，修改
        userData = {};

    var auth = {
        addUser: false,
        delUser: false,
        editUser: false,
        checkUser: false,
        batchImport: false,
        enableUser: false,
    };

    $(function () {

        pageParams = $.extend(true, pageParams, App.pageParams);

        //初始化按钮显示
        auth = $.extend(true, auth, App.initBtnView(top.authBtns || []));

        // 是否有批量导入的权限
        if (auth['batchImport']) {
            initUpload();
        }

        // 是否有查看用户的权限
        if (auth['checkUser']) {
            initTable();
        } else {
            // 是否查看用户信息
            $('.z-table tbody').html('抱歉，您现在没有查看账号的权限');
        }

        getNation();

        eventListen();

    });

    function eventListen() {

        /**=============== 事件监听 ==============================================================================*/

        $(".import").click(function (e) {
            e.preventDefault();
            e.stopPropagation();
            $("input[name=file]").click();
        });

        $('.downloadTemp').click(function () {
            // window.open(App.apiUrlHost + '/sysUser/downloadSysUserTemplate');
            location.href = App.apiUrlHost + '/sysUser/downloadSysUserTemplate';
        });

        $('#doFilter').click(function () {
            doSearchData();
        });

        $('.add-account').click(function () {

            userOptType = 1;
            App.clearForm('.popup-add-acount');
            popup.open('.popup-add-acount');
            $('.popup-add-acount .password').attr('data-rule','required,length');
        });

        // 批量启用
        $('.enable-account, .disable-account, .del-account').click(function () {

            // 检查选取数量
            var checkResult = App.checkTableSelect('mutil');
            if (!checkResult.result) {
                popup.tipsTop({type: 'warning', msg: checkResult.msg});
                return false;
            } else {
                console.log('选择数量检测成功');
            }

            var ids = App.filterByFild(zTable.getSelectedData(), 'userId');

            if ($(this).hasClass('enable-account')) ableUser(ids);
            if ($(this).hasClass('disable-account')) disableUser(ids);
            if ($(this).hasClass('del-account')) delUser(ids);

        });

        // 选择部门按钮
        $('.select-dept').click(function (e) {
            e.preventDefault();
            var $self = $(this);
            layerOpen({
                type: 1,
                title: '选择部门',
                url: './selectDept.html',
                comfirm: (index, layero, layer) => {

                    var $ids = $(layero.find('iframe')).contents().find(".src-ids");
                    var $names = $(layero.find('iframe')).contents().find(".src-names");

                    var idshtml = $ids.html().replace(/\<br\>/g, ',');
                    var namehtml = $names.html().replace(/\<br\>/g, ',');

                    var html = $ids.html().replace(/\<br\>/g, ',');

                    // $self.siblings('input').val(html);

                    $self.siblings('.departmentId').val(idshtml);
                    $self.siblings('.departmentName').val(namehtml);

                    layer.close(index);
                },
                cancel: (index, layero, layer) => {

                    layer.close(index);
                }
            })
        });

        // 选择角色
        $('.select-role').click(function (e) {
            e.preventDefault();
            var $self = $(this);
            layerOpen({
                type: 1,
                title: '选择角色',
                url: './selectRole.html',
                comfirm: (index, layero, layer) => {

                    var $ids = $(layero.find('iframe')).contents().find(".src-ids");
                    var $names = $(layero.find('iframe')).contents().find(".src-names");

                    var idshtml = $ids.html().replace(/\<br\>/g, ',');
                    var namehtml = $names.html().replace(/\<br\>/g, ',');

                    var html = $ids.html().replace(/\<br\>/g, ',');

                    $self.siblings('.roleIds').val(idshtml);
                    $self.siblings('.roleNames').val(namehtml);

                    layer.close(index);
                },
                cancel: (index, layero, layer) => {

                    layer.close(index);
                }
            })
        })


        $("#userForm").form({
            submitSelector: '.user-comfirm',
            msg: function (msg) {
                popup.tips(msg);
            },
            submit: function () {

                var sysUser = {
                    'userId': $('.popup-add-acount [name=userId]').val(),
                    'departmentId': $('.popup-add-acount [name=departmentId]').val(),
                    'userName': $('.popup-add-acount [name=userName]').val(),       // 部门编码
                    // 'password': $('.popup-add-acount [name=password]').val(),
                    'realName': $('.popup-add-acount [name=realName]').val(),
                    'sex': $('.popup-add-acount [name=sex]').val(),
                    'post': $('.popup-add-acount [name=post]').val(),
                    'nation': $('.popup-add-acount [name=nation]').val(),
                    'idCard': $('.popup-add-acount [name=idCard]').val(),
                    'email': $('.popup-add-acount [name=email]').val(),
                    'telephone': $('.popup-add-acount [name=telephone]').val(),
                    'able': 1
                };

                var pw = $('.popup-add-acount [name=password]').val();

                if (pw) {

                    sysUser['password'] = CryptoJS.MD5(pw).toString();
                }

                // 数据整合
                var data = {
                    sysUserJson: JSON.stringify(sysUser),
                    roleIds: $('.popup-add-acount [name=roleIds]').val()
                };

                if (userOptType == 1) {
                    var url = App.apiUrlHost + '/sysUser/saveSysUser';
                } else {
                    var url = App.apiUrlHost + '/sysUser/updateSysUser';

                    data.sysUserJson = JSON.stringify($.extend(true, userData, sysUser));
                }

                submitDeptData(url, data, (result) => {

                    popup.tipsTop({type: 'success', msg: result.msg})

                    popup.close('.popup-add-acount');

                    zTable.resetPage();
                    zTable.reload();

                });

            }
        });

    }

    function initTable() {

        zTable = $('.z-table-con').pagination({
            $pageShowArea: $('.z-page'),
            async: {
                url: App.apiUrlHost + '/sysUser/listPage',// 请求地址
                dataType: 'json',
                type: 'POST',
                data: pageParams // 请求参数
            },
            beforAjax: function (data) {

                pageParams = $.extend(true, pageParams, App.getFilter());
                return {
                    departmentId: pageParams.departmentId,
                    search: pageParams.search,
                    pageNum: parseInt(data.start / pageParams.pageSize, 10) + 1
                }
            },
            columns: [
                {
                    className: 'j-checkbox-col',
                    width: '30px',
                    data: null,
                    render: function (data, type, row, meta) {
                        return '<input type="checkbox" class="j-checkbox" id="' + data.userId + '">';
                    }
                },
                {'data': 'userName', className: 'ellipsis'},
                {'data': 'sexDesc', className: 'ellipsis'},
                {'data': 'departmentName', className: 'ellipsis'},
                {'data': 'roleName', className: 'ellipsis'},
                {'data': 'realName', className: 'ellipsis'},
                {'data': 'email', className: 'ellipsis'},
                {'data': 'telephone', className: 'ellipsis'},
                {'data': 'able', className: 'ellipsis'},
                {'data': 'status', className: 'ellipsis'},
            ],
            beforeCreateRow: function ($row, data, index) {

                var optHtml = '';

                if (auth['editUser']) {
                    optHtml += '<a href="#" classs="edit-acount" onclick="javascript:editUser(\'' + data.userId + '\')">编辑</a>';
                }
                if (auth['delUser']) {
                    optHtml += '<a href="#" onclick="javascript:delUser(\'' + data.userId + '\')">删除</a>';
                }
                if (auth['enableUser']) {

                    if (data.able == '1') {
                        optHtml += '<a href="#" onclick="javascript:disableUser(\'' + data.userId + '\')">停用</a>';
                    } else {
                        optHtml += '<a href="#" onclick="javascript:ableUser(\'' + data.userId + '\')">启用</a>';
                    }
                }

                $('td', $row).eq(9).html(optHtml);

                if (data.able == '1') {

                    $('td', $row).eq(8).addClass('green').html('启用');
                } else {

                    $('td', $row).eq(8).addClass('peru').html('禁用');
                }
                return $row;
            },
            drawCallback: function (setting) {
                // console.log('drawCallback');
            },
            initComplete: function (setting, json) {
                // console.log('initComplete');
            },
            formartData: function (data) {

                return {
                    recordsTotal: data.data.total,
                    data: data.data.list,
                    // pageIndex: data.data.pageNum
                }
            }
        });

        zTable.init();
    }

    function initUpload() {
        uploadFiles = $(".z-btn-group").upload({
            fieldname: 'file',
            url: App.apiUrlHost + '/sysUser/importUserBatch',
            beforeSend: function () {
                const {$element, uploadId, file} = uploadFiles;
                const {uploadType, limit, inputName} = uploadFiles.options;

                const html = `
                            <div class="upload-item" data-id="${uploadId}">
                                <input type="text" name="${inputName}" class="z-hide">
                                <div class="head">
                                    <a class="name" target="_blank">${file.name}</a>
                                    <div class="close fa fa-close"></div>
                                </div>
                                <div class="progress">
                                    <div class="progress-outer">
                                        <div class="progress-inner">
                                            <div class="progress-bg" style="width: 0%; height: 8px;"></div>
                                        </div>
                                    </div>
                                    <div class="progress-text">0%</div>
                                </div>

                            </div>
                  `;

                if (limit == 1) {
                    $element.find('.upload-list').html(html);
                } else {
                    $element.find('.upload-list').append(html);
                }

                uploadFiles.$uploadName = $element.find(`.upload-item[data-id=${uploadId}] .name`);
                uploadFiles.$progress = $element.find(`.upload-item[data-id=${uploadId}] .progress`);
                uploadFiles.$progressBg = $element.find(`.upload-item[data-id=${uploadId}] .progress-bg`);
                uploadFiles.$progressText = $element.find(`.upload-item[data-id=${uploadId}] .progress-text`);
                uploadFiles.$inputFile = $element.find(`.upload-item[data-id=${uploadId}] input`);
            },
            success: function (result) {
                const {$element, uploadId} = uploadFiles;
                if (result.code == 0) {
                    zTable.init();
                    popup.tipsTop({type: 'success', msg: result.msg})
                    // progressSet(1, {url: result.data[0].file})
                } else {
                    popup.tipsTop({type: 'error', msg: result.msg})
                    // progressSet(2)
                }
            },
            error: function (err) {
                // progressSet(3, {msg: err})
            },
            progress: function ({percentage}) {
                // progressSet(0, {percentage})
            },
            recursion: true,
        })
    }

    // 帅选数据
    function doSearchData() {

        zTable.resetPage();
        zTable.reload();

    }

    // 删除用户
    function delUser(id) {

        if (confirm('确认是否删除？')) {

            // var userId = id;
            var url = App.apiUrlHost + '/sysUser/deleteSysUser';
            var params = {userId: id};

            if (typeof id === 'object') {
                // userId = id.join(',');
                url = App.apiUrlHost + '/sysUser/batchDeleteSysUser';
                params = {userIds: id.join(',')}
            }

            App.getData({
                url: url,
                data: params,
                dataType: 'json',
                success: function (result) {

                    if (result.code == 0) {

                        popup.tipsTop({type: 'success', msg: result.msg})

                        zTable.init();

                    } else {
                        popup.tipsTop({type: 'error', msg: result.msg})
                    }
                }
            })

        }

    }

    // 停用用户
    function disableUser(id) {

        if (!id) return;

        if (confirm('确认是否停用')) {

            var userId = typeof id === 'string' ? id : id.join(',');
            var url = App.apiUrlHost + '/sysUser/disable';
            App.getData({
                url: url,
                data: {userId: userId},
                dataType: 'json',
                success: function (result) {

                    if (result.code == 0) {

                        popup.tipsTop({type: 'success', msg: result.msg})

                        zTable.init();

                    } else {
                        popup.tipsTop({type: 'error', msg: result.msg})
                    }
                }
            })
        }

    }


    // 启用用户
    function ableUser(id) {

        if (!id) return;

        if (confirm('确认是否启用')) {

            var userId = typeof id === 'string' ? id : id.join(',');
            var url = App.apiUrlHost + '/sysUser/enable';
            App.getData({
                url: url,
                data: {userId: userId},
                dataType: 'json',
                success: function (result) {

                    if (result.code == 0) {

                        popup.tipsTop({type: 'success', msg: result.msg})
                        zTable.init();

                    } else {
                        popup.tipsTop({type: 'error', msg: result.msg})
                    }
                }
            })
        }

    }

    // 编辑用户
    function editUser(id) {

        userOptType = 2;
        $('.popup-add-acount .password').attr('data-rule','');

        //todo 获取当前选中用户信息
        var userId = id;
        var url = App.apiUrlHost + '/sysUser/getById';
        App.getData({
            url: url,
            data: {userId: userId},
            dataType: 'json',
            success: function (result) {

                if (result.code == 0) {

                    userData = result.data;
                    App.fillForm('.popup-add-acount', result.data);
                    $('.popup-add-acount [name=sex]').val(result.data.sex);
                    $('.popup-add-acount [name=password]').val('');
                    $('.popup-add-acount [name=roleIds]').val(result.data.roleId);
                    $('.popup-add-acount [name=roleNames]').val(result.data.roleName);
                    popup.open('.popup-add-acount');

                } else {
                    popup.tipsTop({type: 'error', msg: result.msg})
                }
            }
        })

    }

    // 检测选中数量
    function checkSelect() {
        var checkResult = zTree.tree.getSelectedNodes();

        if (checkResult.length <= 0) {
            popup.tipsTop({type: 'warning', msg: '请选择要修改的部门'})
            return false;
        } else {
            console.log('选择数量检测成功');
            return true;
        }
    }

    function getNation() {
        App.getData({
            url: App.apiUrlHost + '/sysUser/listNation',
            data: {},
            dataType: 'json',
            success: function (result) {

                if (result.code == 0) {

                    nations = result.data;

                    var html = '<option value="">--请选择--</option>';

                    for (var i = 0; i < nations.length; i++) {
                        html += '<option value="' + nations[i] + '">' + nations[i] + '</option>'
                    }

                    $('.popup-add-acount .nation').html(html);

                } else {
                    popup.tipsTop({type: 'error', msg: result.msg})
                }
            }
        })
    }

    // 提交部门信息
    function submitDeptData(url, data, callback) {

        App.getData({
            url: url,
            data: data,
            dataType: 'json',
            success: function (result) {

                if (result.code == 0 && callback && typeof callback == 'function') {
                    callback(result);
                } else {
                    popup.tipsTop({type: 'error', msg: result.msg})
                }
            }
        })
    }

</script>
<script th:src="@{/lib/flatpickr/flatpickr.js}"></script>
<script th:src="@{/lib/flatpickr/zh.js}"></script>
<script>
    flatpickr.localize(flatpickr.l10ns.zh); // 设置为中文
    flatpickr(".flatpickr-hour", {
        enableTime: true,
        noCalendar: true,
        dateFormat: "H:i",
        time_24hr: true
    });
</script>
</body>